"use client";
import { defaultEditorContent } from "@/lib/content";
import {
  EditorCommand,
  EditorCommandEmpty,
  EditorCommandItem,
  EditorCommandList,
  EditorContent,
  type EditorInstance,
  EditorRoot,
  type JSONContent,
} from "novel";
import { ImageResizer, handleCommandNavigation } from "novel/extensions";
import { useEffect, useState } from "react";
import { useDebouncedCallback } from "use-debounce";
import { defaultExtensions } from "./extensions";
import { ColorSelector } from "./selectors/color-selector";
import { LinkSelector } from "./selectors/link-selector";
import { NodeSelector } from "./selectors/node-selector";
import { MathSelector } from "./selectors/math-selector";
import { Separator } from "./ui/separator";

import { handleImageDrop, handleImagePaste } from "novel/plugins";
import GenerativeMenuSwitch from "./generative/generative-menu-switch";
import { uploadFn } from "./image-upload";
import { TextButtons } from "./selectors/text-buttons";
import { slashCommand, suggestionItems } from "./slash-command";

const hljs = require('highlight.js');

const extensions = [...defaultExtensions, slashCommand];

const TailwindAdvancedEditor = () => {
  const [initialContent, setInitialContent] = useState<null | JSONContent>(null);
  const [saveStatus, setSaveStatus] = useState("Saved");
  const [charsCount, setCharsCount] = useState();

  const [openNode, setOpenNode] = useState(false);
  const [openColor, setOpenColor] = useState(false);
  const [openLink, setOpenLink] = useState(false);
  const [openAI, setOpenAI] = useState(false);
  const [test, setTest] = useState("");

  //Apply Codeblock Highlighting on the HTML from editor.getHTML()
  const highlightCodeblocks = (content: string) => {
    const doc = new DOMParser().parseFromString(content, 'text/html');
    doc.querySelectorAll('pre code').forEach((el) => {
      // @ts-ignore
      // https://highlightjs.readthedocs.io/en/latest/api.html?highlight=highlightElement#highlightelement
      hljs.highlightElement(el);
    });
    return new XMLSerializer().serializeToString(doc);
  };
  var md = []
  const debouncedUpdates = useDebouncedCallback(async (editor: EditorInstance) => {
    const json = editor.getJSON();
    setCharsCount(editor.storage.characterCount.words());
    window.localStorage.setItem("html-content", highlightCodeblocks(editor.getHTML()));
    window.localStorage.setItem("novel-content", JSON.stringify(json));
    window.localStorage.setItem("outline", JSON.stringify(json));
    window.parent.postMessage(JSON.stringify(json), '*');
    window.localStorage.setItem("markdown", editor.storage.markdown.getMarkdown());
    setSaveStatus("Saved");
  }, 500);

  const markdownToTiptap = (markdown, type) => {
    const json = {
      type: 'doc',
      content: []
    };
    const lines = type == 'two' ? markdown.split('\n') : markdown.split('\n\n');
    let currentBlock = null;

    lines.forEach((line, index) => {
      // 过滤掉空行，避免创建空的文本节点
      if (line.trim() === '') {
        return;
      }

      if (line.startsWith('# ')) {
        const text = line.slice(2);
        const heading = {
          type: 'heading',
          attrs: { level: 1 },
          content: [{ type: 'text', text }]
        };
        json.content.push(heading);
        currentBlock = heading;
      } else if (line.startsWith('## ')) {
        const text = line.slice(3);
        const heading = {
          type: 'heading',
          attrs: { level: 2 },
          content: [{ type: 'text', text }]
        };
        json.content.push(heading);
        currentBlock = heading;
      } else if (line.startsWith('### ')) {
        const text = line.slice(4);
        const heading = {
          type: 'heading',
          attrs: { level: 3 },
          content: [{ type: 'text', text }]
        };
        json.content.push(heading);
        currentBlock = heading;
      } else if (line.startsWith('- [ ]')) {
        // 任务列表（未完成）
        const taskListItem = {
          type: 'listItem',
          content: [{ type: 'text', text: line.slice(5) }],
          attrs: { done: false }
        };
        if (json.content.length === 0 || json.content[json.content.length - 1].type !== 'taskList') {
          json.content.push({
            type: 'taskList',
            content: [taskListItem]
          });
        } else {
          json.content[json.content.length - 1].content.push(taskListItem);
        }
        currentBlock = taskListItem;
      } else if (line.startsWith('- [x]')) {
        // 任务列表（已完成）
        const taskListItem = {
          type: 'listItem',
          content: [{ type: 'text', text: line.slice(5) }],
          attrs: { done: true }
        };
        if (json.content.length === 0 || json.content[json.content.length - 1].type !== 'taskList') {
          json.content.push({
            type: 'taskList',
            content: [taskListItem]
          });
        } else {
          json.content[json.content.length - 1].content.push(taskListItem);
        }
        currentBlock = taskListItem;
      } else if (line.startsWith('- ')) {
        // 无序列表
        const listItem = {
          type: 'listItem',
          content: [{ type: 'text', text: line.slice(2) }]
        };
        if (json.content.length === 0 || json.content[json.content.length - 1].type !== 'bulletList') {
          json.content.push({
            type: 'bulletList',
            content: [listItem]
          });
        } else {
          json.content[json.content.length - 1].content.push(listItem);
        }
        currentBlock = listItem;
      } else if (/^\d+\. /.test(line)) {
        // 有序列表
        const listItem = {
          type: 'listItem',
          content: [{ type: 'text', text: line.replace(/^\d+\. /, '') }]
        };
        if (json.content.length === 0 || json.content[json.content.length - 1].type !== 'orderedList') {
          json.content.push({
            type: 'orderedList',
            content: [listItem]
          });
        } else {
          json.content[json.content.length - 1].content.push(listItem);
        }
        currentBlock = listItem;
      } else if (line.startsWith('![') && line.includes('](') && line.includes(')')) {
        // 图片
        const parts = line.split('](');
        const alt = parts[0].slice(2);
        const src = parts[1].slice(0, -1);
        const image = {
          type: 'image',
          attrs: { src, alt }
        };
        json.content.push(image);
        currentBlock = image;
      } else if (line.startsWith('```')) {
        // 代码块（开始和结束标记）
        const codeBlock = {
          type: 'codeBlock',
          content: [{ type: 'text', text: lines[index + 1] }]
        };
        json.content.push(codeBlock);
        currentBlock = codeBlock;
      } else if (line.startsWith('> ')) {
        // 引用块
        const text = line.slice(2);
        const blockquote = {
          type: 'blockquote',
          content: [{ type: 'paragraph', content: [{ type: 'text', text }] }]
        };
        json.content.push(blockquote);
        currentBlock = blockquote;
      } else if (line.startsWith('~~') && line.endsWith('~~')) {
        // 删除线
        const text = line.slice(2, -2);
        const strike = {
          type: 'text',
          marks: [{ type: 'strike' }],
          text
        };
        json.content.push({ type: 'paragraph', content: [strike] });
        currentBlock = strike;
      } else if (line === '---' || line === '***' || line === '___') {
        // 分割线
        const horizontalRule = {
          type: 'horizontalRule'
        };
        json.content.push(horizontalRule);
        currentBlock = horizontalRule;
      } else if (line.trim() !== '') {
        // 普通段落
        const paragraph = {
          type: 'paragraph',
          content: [{ type: 'text', text: line }]
        };
        json.content.push(paragraph);
        currentBlock = paragraph;
      } else if (line.trim() === '' && currentBlock && currentBlock.type === 'paragraph') {
        // 换行
        json.content.push({ type: 'hardBreak' });
      }
    });

    return json;
  };
  useEffect(() => {
    let messageHandled = false;
    const handleMessage = (event) => {
      md = event.data.outline
      if (event.data.type === 'two') {
        console.log(md);
        window.localStorage.setItem("md", JSON.stringify(md));
        // 检查 md 是不是一个数组
        if (Array.isArray(md)) {
          messageHandled = true
          // md = md.map(line => line.replace(/"/g, "\n"));
          md = md.filter((line) => line != '');
          md = md.join('\n');  // 将数组转换为字符串
          console.log(md);
        }
        const content = markdownToTiptap(md, 'two')
        window.parent.postMessage(JSON.stringify(content), '*');
        window.localStorage.setItem("outline", JSON.stringify(content));
        setInitialContent(JSON.parse(window.localStorage.getItem("outline")));
      }
      if (event.data.type === 'three') {
        console.log(md)
        debugger
        const content = markdownToTiptap(md, 'three')
        console.log(content);
        window.parent.postMessage(JSON.stringify(content), '*');
        window.localStorage.setItem("outline2", JSON.stringify(content));
        setInitialContent(JSON.parse(window.localStorage.getItem("outline2")));
      }
    };
    window.addEventListener('message', handleMessage);
    let str: String = `#### 1、Introduction
##### In the field of computer vision,
#### 2、Overview
##### The core idea behind Multi-Stage Progressive Image Restoration
`;
    // if (!messageHandled) {
    //   if (window.localStorage.getItem("outline")) {
    //     console.log(JSON.parse(window.localStorage.getItem("outline")));
    //     debugger
    //     setInitialContent(JSON.parse(window.localStorage.getItem("outline")));
    //   }
    //   else {
    //     setInitialContent(str);
    //   }
    // }




    // else setInitialContent(defaultEditorContent);
    // 清理事件监听器
    return () => {
      window.removeEventListener('message', handleMessage);
    };
  }, []);

  if (!initialContent) return null;
  return (
    <div className="relative w-full g_border">
      {/* <div className="flex absolute right-5 top-5 z-10 mb-5 gap-2">
        <div className="rounded-lg bg-accent px-2 py-1 text-sm text-muted-foreground">{saveStatus}</div>
        <div className={charsCount ? "rounded-lg bg-accent px-2 py-1 text-sm text-muted-foreground" : "hidden"}>
          {charsCount} Words
        </div>
      </div> */}
      <EditorRoot>
        <EditorContent
          initialContent={initialContent}
          extensions={extensions}
          className="relative min-h-[453px] w-full bg-background sm:rounded-lg sm:border sm:shadow-lg bd_color"
          editorProps={{
            handleDOMEvents: {
              keydown: (_view, event) => handleCommandNavigation(event),
            },
            handlePaste: (view, event) => handleImagePaste(view, event, uploadFn),
            handleDrop: (view, event, _slice, moved) => handleImageDrop(view, event, moved, uploadFn),
            attributes: {
              class:
                "prose prose-lg dark:prose-invert prose-headings:font-title font-default focus:outline-none max-w-full",
            },
          }}
          onUpdate={({ editor }) => {
            debouncedUpdates(editor);
            setSaveStatus("Unsaved");
          }}
          slotAfter={<ImageResizer />}
        >
          {/* <EditorCommand className="z-50 h-auto max-h-[330px] overflow-y-auto rounded-md border border-muted bg-background px-1 py-2 shadow-md transition-all"> */}
          {/* <EditorCommandEmpty className="px-2 text-muted-foreground">No results</EditorCommandEmpty> */}
          {/* <EditorCommandList>
              {suggestionItems.map((item) => (
                <EditorCommandItem
                  value={item.title}
                  onCommand={(val) => item.command(val)}
                  className="flex w-full items-center space-x-2 rounded-md px-2 py-1 text-left text-sm hover:bg-accent aria-selected:bg-accent"
                  key={item.title}
                >
                  <div className="flex h-10 w-10 items-center justify-center rounded-md border border-muted bg-background">
                    {item.icon}
                  </div>
                  <div>
                    <p className="font-medium">{item.title}</p>
                    <p className="text-xs text-muted-foreground">{item.description}</p>
                  </div>
                </EditorCommandItem>
              ))}
            </EditorCommandList> */}
          {/* </EditorCommand> */}

          <GenerativeMenuSwitch open={openAI} onOpenChange={setOpenAI}>
            <Separator orientation="vertical" />
            {/* <NodeSelector open={openNode} onOpenChange={setOpenNode} /> */}
            {/* <Separator orientation="vertical" /> */}

            {/* <LinkSelector open={openLink} onOpenChange={setOpenLink} />
            <Separator orientation="vertical" />
            <MathSelector />
            <Separator orientation="vertical" />
            <TextButtons />
            <Separator orientation="vertical" />
            <ColorSelector open={openColor} onOpenChange={setOpenColor} /> */}
          </GenerativeMenuSwitch>
        </EditorContent>
      </EditorRoot>
    </div>
  );
};

export default TailwindAdvancedEditor;